<template>
  <div class="submitPresent">
    <x-header class="header" :left-options="{showBack: showHeaderBack}" ref="header">提交赠送</x-header>
    <div class="topHolder"></div>
    <group title="订单信息：">
      <cell title="房台号码" :value="orderInfo.AREA + ' - ' + orderInfo.NUMBER + '（' + orderInfo.ROOM_PLATFORM_TYPE + '）'"></cell>
      <cell title="订单单号" class="number" :value="orderInfo.ORDER_NUMBER"></cell>
      <cell title="客户名称" :value="orderInfo.CUSTOMER_NAME"></cell>
      <cell title="赠送人" :value="userInfo.NAME"></cell>
    </group>
    <group title="赠送列表：">
      <cell-box v-for="(item,index) in selectItems" :key="index">
        <div class="item">
          <div class="item-content">
            <div class="item-left">
              <a class="img"><img :src="contextPath + item.IMAGE" :onerror="defaultImg" /></a>
            </div>
            <div class="item-right">
              <span class="title" v-text="item.NAME"></span>
              <span class="num"> X&nbsp;<span v-text="item.QUANTITY + item.UNIT"></span></span>
              <span class="price">
                ¥&nbsp;<span v-text="formatCurrency(item.PRICE*item.QUANTITY)"></span>元
              </span>
              <br/>
              <span class="matchDrink" v-if="item.MATCHINGDRINK.replace(/\s+/g,'') != ''">
                &nbsp;[ 配饮：<span v-text="item.choosenMatchingDrink.MATCHINGDRINK_NAME + ' X ' + item.choosenMatchingDrink.MATCHINGDRINK_NUM"></span> ]
              </span>
              <div class="setMeal" v-if="item.choosenMealSetItems && item.choosenMealSetItems.length > 0">
                已选套餐内容：<br/>
                <div class="setMealItem" v-for="(setMealItem,setMealIndex) in item.choosenMealSetItems" :key="setMealIndex">
                  <i class="el-icon-caret-right"></i>
                  <span v-text="setMealItem.NAME"></span>&nbsp;X&nbsp;<span v-text="setMealItem.QUANTITY + setMealItem.UNIT"></span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </cell-box>
      <div class="totals">
        共 <span v-text="countUp"></span> 件商品，合计：<span class="price">¥&nbsp;<span v-text="formatCurrency(addUp)"></span>元</span>
      </div>
    </group>
    <group title="赠送备注(选填)：">
      <x-textarea :max="200" v-model="remark" placeholder="点击输入"></x-textarea>
    </group>
    <box gap="1rem 0.8rem">
      <x-button :gradients="['#FF2719', '#FF61AD']" @click.native="submit" :show-loading="loadingStatus" :disabled="loadingStatus" text="提交赠送"></x-button>
    </box>
  </div>
</template>

<script>
  import {Group, Cell, CellBox, XTextarea, Box, XButton,numberComma } from 'vux'
  import {getOrderDetail,getUserInfo,submitPresent,contextPath} from "../../api";
  import {message,toDecimal2} from "../../common/util";

  export default {
    name:'submitPresent',
    data(){
      return{
        showHeaderBack:this.GLOBAL.showHeaderBack,
        paramOrderId:this.$route.params.orderId,
        paramType:this.$route.params.type,
        loadingStatus:true,
        contextPath:contextPath,
        defaultImg:"this.src= '" + require('../../assets/images/defaultGoodImg-thumb.jpg') +"'",
        orderInfo:{},
        userInfo:{},
        remark:'',
        selectItems:[]
      }
    },
    components:{
      Group,
      Cell,
      CellBox,
      XTextarea,
      Box,
      XButton
    },
    computed:{
      salesSelectedList:{
        get () {
          return this.$store.getters.getSalesSelectedList
        },
        set (value) {
          this.$store.commit('updateSalesSelectedList', value)
        }
      },
      keepSelectedList:{
        get () {
          return this.$store.getters.getKeepSelectedList
        },
        set (value) {
          this.$store.commit('updateKeepSelectedList', value)
        }
      },
      girlSelectedList:{
        get () {
          return this.$store.getters.getGirlSelectedList
        },
        set (value) {
          this.$store.commit('updateGirlSelectedList', value)
        }
      },
      addUp(){
        let total = 0
        for(let item of this.selectItems){
          total = total + item.PRICE*item.QUANTITY
        }
        return total
      },
      countUp(){
        let count = 0
        for(let item of this.selectItems){
          count = count + 1*item.QUANTITY
        }
        return count
      }
    },
    methods:{
      formatCurrency(number){
        return numberComma(toDecimal2(number))
      },
      submit(){
        let flag = false,allGoodIds = [],tempList = JSON.parse(JSON.stringify(this.selectItems))//用HTML5的JSON方法解决js对象的引用的问题
        tempList.forEach((item, key, array)=>{
          /*if(item.choosenMatchingDrink){//提交时候，传输所有配饮的实际数量
            item.choosenMatchingDrink.MATCHINGDRINK_NUM = item.choosenMatchingDrink.MATCHINGDRINK_NUM * item.number
          }*/
          allGoodIds.push(item.GOODS_ID)
          if(item.choosenMatchingDrink && item.choosenMatchingDrink != '')
            allGoodIds.push(item.choosenMatchingDrink.MATCHINGDRINK_ID)
          for(let cMSItem of item.choosenMealSetItems){
            allGoodIds.push(cMSItem.GOODS_ID)
          }
          array[key].choosenMatchingDrink = item.choosenMatchingDrink == ''?'':JSON.stringify(item.choosenMatchingDrink)
          array[key].choosenMealSetItems = item.choosenMealSetItems.length > 0?JSON.stringify(item.choosenMealSetItems):[]
        })
        if(flag) return false
        this.$vux.confirm.show({
          title:'确认赠送',
          content:'是否确认赠送所选商品？',
          onCancel: ()=> {
            this.loadingStatus = false
          },
          onConfirm: ()=> {
            let reqParams = {
              orderId:this.paramOrderId,
              type:this.paramType,
              selectItems:tempList,
              remark:this.remark,
              allGoodIds: allGoodIds
            }
            submitPresent(reqParams).then((res)=>{
              if(res.status == 'success'){
                switch (this.paramType) {
                  case 'salePresent':this.salesSelectedList = [];break
                  case 'keepPresent':this.keepSelectedList = [];break
                  case 'girlPresent':this.girlSelectedList = [];break
                  default:break
                }
                this.$router.push({path:'/presentedList'})
              }else if(res.status == 'error') {
                message({message:res.msg,type:'error'})
                console.log('submitPresent error info:', res.msg)
              }
            }).catch((err)=>{console.log('submitPresent catch info:',err)})
          }
        })
      }
    },
    mounted(){
      if((this.paramType == 'salePresent' && this.salesSelectedList.length <= 0) ||
        (this.paramType == 'keepPresent' && this.keepSelectedList.length <= 0) ||
        (this.paramType == 'girlPresent' && this.girlSelectedList.length <= 0))
        this.$router.push({path:'/presentManager'})
      Promise.all([getUserInfo(),getOrderDetail(this.paramOrderId)]).then((res)=>{
        if(res[0].status == 'success'){
          this.userInfo = res[0].data
        }else if(res[0].status == 'error'){
          console.log('getUserInfo error info:',res[0].msg)
          message({message:res[0].msg,type: 'error'})
        }
        if(res[1].status == 'success'){
          this.orderInfo = res[1].data
        }else if(res[1].status == 'error') {
          message({message:res[1].msg,type:'error'})
          console.log('getOrderDetail error info:', res[1].msg)
        }
      }).then(()=>{
        if(this.paramType == 'salePresent'){
          this.selectItems = this.salesSelectedList
        }else if(this.paramType == 'keepPresent'){
          this.selectItems = this.keepSelectedList
        }else if(this.paramType == 'girlPresent'){
          this.selectItems = this.girlSelectedList
        }
        this.loadingStatus = false
        this.$store.commit('updateLoadingStatus',{isLoading:false})
      }).catch((err)=>{console.log('getUserInfo or getOrderDetail catch info:',err)})
    }
  }
</script>

<style lang="scss" scoped>
  .submitPresent{
    .item{
      overflow: hidden;width: 100%;background: #fff;
      .item-content{
        display:flex;min-height: 4rem;
        .item-left{
          font-size: 0;width: 5rem;margin-right: 0.5rem;
          .img{
            img{width: 100%;height: 100%;max-height: 4rem;}
          }
        }
        .item-right{
          line-height: 1.35rem;-webkit-box-flex: 1;-webkit-flex: 1;flex: 1;font-size: 0.9rem;color: #666;position: relative;
          .title{width:100%;overflow: hidden;display: -webkit-box;-webkit-line-clamp: 1;-webkit-box-orient: vertical;}
          .num{}
          .price{font-size: 0.9rem;color: #a9534c;position: absolute;top: 1.25rem;right: 0;}
          .matchDrink{color:#7e7e7e;font-size:0.7rem;line-height: 0.9rem;}
          .setMeal{
            padding: 0.5rem 0;font-size: 0.7rem;color: #9a9a9a;line-height: 0.9rem;
            .setMealItem{margin-top: 0.3rem;}
          }
        }
      }
    }
    .totals{
      border-top: 1px solid #eee;padding:1rem 15px;text-align: right;font-size: 1rem;
      .price{color: #a9534c;}
    }
  }
</style>
